package com.jinwei.qunguanjia.security.filter;

import com.jinwei.qunguanjia.common.constant.CacheConstants;
import com.jinwei.qunguanjia.common.core.domain.model.LoginTenant;
import com.jinwei.qunguanjia.common.core.domain.model.LoginUser;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.utils.SystemContextUtils;
import com.jinwei.qunguanjia.common.utils.TenantContextUtils;
import com.jinwei.qunguanjia.system.dto.SysLoginUser;
import com.jinwei.qunguanjia.system.utils.SecurityUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import com.jinwei.qunguanjia.system.service.TokenService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Nonnull;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 * 
 * @author yuanzs
 */
@Component

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    private final RedisCache redisCache;

    private final TokenService tokenService;

    public JwtAuthenticationTokenFilter(RedisCache redisCache, TokenService tokenService) {
        this.redisCache = redisCache;
        this.tokenService = tokenService;
    }

    @Override
    protected void doFilterInternal(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull FilterChain chain)
            throws ServletException, IOException
    {
        SysLoginUser sysLoginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(sysLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            LoginUser loginUser = new LoginUser();
            loginUser.setUserName(sysLoginUser.getUsername());
            BeanUtils.copyProperties(sysLoginUser, loginUser);
            SystemContextUtils.setCurrentSystemUser(loginUser);
            String tenantId = tokenService.getTenantId(request);
            LoginTenant loginTenant = redisCache.getCacheObject(CacheConstants.LOGIN_TENANT_KEY + tenantId);
            TenantContextUtils.setCurrentTenant(loginTenant);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysLoginUser, null, sysLoginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
